package com.example.neutonote2.ui.categories;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.neutonote2.R;
import com.example.neutonote2.data.model.Category;
import com.example.neutonote2.viewmodel.CategoryViewModel;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import java.util.ArrayList;
import java.util.List;

public class CategoryListFragment extends Fragment {

    private CategoryViewModel categoryViewModel;
    private RecyclerView recyclerView;
    private TextView textNoCategories;
    private FloatingActionButton fabAddCategory;

    // 定义分类点击监听器接口
    interface OnCategoryClickListener {
        void onCategoryClick(Category category);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_category_list, container, false);

        recyclerView = root.findViewById(R.id.recycler_view_categories);
        textNoCategories = root.findViewById(R.id.text_no_categories);
        fabAddCategory = root.findViewById(R.id.fab_add_category);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(new CategoryAdapter(new ArrayList<>(), category -> {
        }));

        fabAddCategory.setOnClickListener(v -> showAddCategoryDialog());

        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 初始化ViewModel
        categoryViewModel = new ViewModelProvider(requireActivity()).get(CategoryViewModel.class);

        // 加载分类
        categoryViewModel.getAllCategories().observe(getViewLifecycleOwner(), categories -> {
            if (categories != null && !categories.isEmpty()) {
                textNoCategories.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
                ((CategoryAdapter) recyclerView.getAdapter()).updateCategories(categories);
            } else {
                textNoCategories.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            }
        });
    }

    private void showAddCategoryDialog() {
        // 创建对话框布局
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_category, null);
        TextInputEditText editCategoryName = dialogView.findViewById(R.id.edit_category_name);
        TextInputLayout layoutCategoryName = dialogView.findViewById(R.id.layout_category_name);

        // 显示对话框
        new MaterialAlertDialogBuilder(requireContext())
                .setTitle("新建分类")
                .setView(dialogView)
                .setPositiveButton("保存", (dialog, which) -> {
                    String name = editCategoryName.getText().toString().trim();

                    if (name.isEmpty()) {
                        layoutCategoryName.setError("请输入分类名称");
                        return;
                    }

                    // 保存分类
                    Category newCategory = new Category(name, "folder", false);
                    categoryViewModel.insert(newCategory);
                    Toast.makeText(requireContext(), "分类已创建", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    // 内部适配器类
    private class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.CategoryViewHolder> {
        private List<Category> categories;
        private final OnCategoryClickListener listener;

        public CategoryAdapter(List<Category> categories, OnCategoryClickListener listener) {
            this.categories = categories;
            this.listener = listener;
        }

        public void updateCategories(List<Category> newCategories) {
            this.categories = newCategories;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public CategoryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            // 使用自定义布局
            View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_category, parent, false);
            return new CategoryViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull CategoryViewHolder holder, int position) {
            Category category = categories.get(position);
            holder.categoryName.setText(category.getName());
            
            // 禁止编辑或删除默认分类
            boolean isDefault = category.isDefault();
            
            // 点击事件 - 编辑分类
            holder.itemView.setOnClickListener(v -> {
                if (!isDefault) {
                    showEditCategoryDialog(category);
                } else {
                    Toast.makeText(requireContext(), "默认分类不能编辑", Toast.LENGTH_SHORT).show();
                }
            });
            
            // 长按事件 - 删除分类
            holder.itemView.setOnLongClickListener(v -> {
                if (!isDefault) {
                    new MaterialAlertDialogBuilder(requireContext())
                        .setTitle("删除分类")
                        .setMessage("确定要删除分类 \"" + category.getName() + "\" 吗？")
                        .setPositiveButton("删除", (dialog, which) -> {
                            categoryViewModel.delete(category);
                            Toast.makeText(requireContext(), "分类已删除", Toast.LENGTH_SHORT).show();
                        })
                        .setNegativeButton("取消", null)
                        .show();
                } else {
                    Toast.makeText(requireContext(), "默认分类不能删除", Toast.LENGTH_SHORT).show();
                }
                return true;
            });
        }

        @Override
        public int getItemCount() {
            return categories.size();
        }

        class CategoryViewHolder extends RecyclerView.ViewHolder {
            TextView categoryName;
            ImageView categoryIcon;
            
            public CategoryViewHolder(@NonNull View itemView) {
                super(itemView);
                categoryName = itemView.findViewById(R.id.text_category_name);
                categoryIcon = itemView.findViewById(R.id.image_category_icon);
            }
        }
    }
    
    /**
     * 显示编辑分类对话框
     */
    private void showEditCategoryDialog(Category category) {
        // 创建对话框布局
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_category, null);
        TextInputEditText editCategoryName = dialogView.findViewById(R.id.edit_category_name);
        TextInputLayout layoutCategoryName = dialogView.findViewById(R.id.layout_category_name);
        
        // 设置现有值
        editCategoryName.setText(category.getName());

        // 显示对话框
        new MaterialAlertDialogBuilder(requireContext())
                .setTitle("编辑分类")
                .setView(dialogView)
                .setPositiveButton("保存", (dialog, which) -> {
                    String name = editCategoryName.getText().toString().trim();

                    if (name.isEmpty()) {
                        layoutCategoryName.setError("请输入分类名称");
                        return;
                    }

                    // 更新分类
                    category.setName(name);
                    categoryViewModel.update(category);
                    Toast.makeText(requireContext(), "分类已更新", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }
} 